package com.tusiyou.homework;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private FrameLayout container;
    private RadioGroup radioGroup;
    private List<Fragment> mFragments;
    private int oldIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        radioGroup = (RadioGroup) findViewById(R.id.rg);

        initData();


        oldIndex = 0;
        RadioButton rb = (RadioButton) radioGroup.getChildAt(oldIndex);
        rb.setChecked(true);
        showFragment(0, oldIndex);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb = (RadioButton) group.findViewById(checkedId);
                int index = group.indexOfChild(rb);

                showFragment(index, oldIndex);
                oldIndex = index;
            }
        });

    }

    private void showFragment(int index, int oldIndex) {
        Fragment showFragment = mFragments.get(index);
        Fragment hideFragment = mFragments.get(oldIndex);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (!showFragment.isAdded()) {
            ft.add(R.id.container, showFragment);
        }
        if (index == oldIndex) {
            ft.show(showFragment);
        } else {
            ft.show(showFragment).hide(hideFragment);
        }
        ft.commit();
    }

    private void initData() {
        mFragments = new ArrayList<Fragment>();
        mFragments.add(new HomeFragment());
        mFragments.add(new HotFragment());
        mFragments.add(new SearchFragment());
        mFragments.add(new MeFragment());

    }
}
